//
//  StatusPictureView.swift
//  Weibo
//
//  Created by 张远文 on 16/4/30.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let PictureCellId = "PictureCellId"
private let PictureCellMargin: CGFloat = 5

class StatusPictureView: UICollectionView {

    
    var imageURLs: [NSURL]? {
    
        didSet {
         
            //刷新数据
            reloadData()
            let viewSize = self.calceViewSize()
            
            self.snp_updateConstraints { (make) in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            
            testLabel.text = "\(imageURLs?.count ?? 0)"
        }
    }
    
    //计算配图视图大小
    private func calceViewSize() -> CGSize {
        //获取配图最大宽度
        let colum: CGFloat = 3.0000000000001
        let maxWidth = screenW - 2 * statusCellMargin
        
        //获取单个图片宽度
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置cell的大小
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        let imageCount = imageURLs?.count ?? 0
        if imageCount == 0 {
            return CGSizeZero
        }
        
        //单张图片
        if imageCount == 1 {
            
            //获取单张被缓存的图片
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            let imageSize = image.size
            layout.itemSize = imageSize
            return imageSize
        }
        
        //四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            return CGSizeMake(w, w)
        }
        
        //多图
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = row * itemWidth + (row - 1) * PictureCellMargin
        return CGSizeMake(w, h)
    }
    
    //重写构造方法,调用设置UI方法
    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        //设置layout,行列间距
        layout.minimumLineSpacing = PictureCellMargin
        layout.minimumInteritemSpacing = PictureCellMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册cell
        registerClass(PictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        
        //设置自己为自己的数据源
        dataSource = self
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setupUI() {
        
        backgroundColor = UIColor.randomColor()
        addSubview(testLabel)
        
        testLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self.snp_center)
        }
        
    }
    
    //懒加载所有控件
    private lazy var testLabel: UILabel = {
       
        let l = UILabel()
        
        l.font = UIFont.systemFontOfSize(25)
        l.textColor = UIColor.redColor()
        l.sizeToFit()
        
        return l
    }()

}

//类扩展继承数据源方法
extension StatusPictureView: UICollectionViewDataSource {
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureCell
        
        //设置cell属性
        cell.url = imageURLs![indexPath.item]
        return cell
    }
}

//自定义cell
class PictureCell: UICollectionViewCell {
    
    var url: NSURL? {
        
        didSet {
            imageView.sd_setImageWithURL(url, placeholderImage: nil)
        }
    }
    
    
    
    
    //重写构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setupUI() {
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //懒加载所有控件
    private lazy var imageView: UIImageView = {
        
        let iv = UIImageView()
        //设置图片显示样式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        //手写代码,必须手动添加裁剪
        iv.clipsToBounds = true
        return iv
    }()
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}